package com.soriya.nestlive.repository

import com.soriya.nestlive.model.Live
import com.soriya.nestlive.model.ResponseResult
import com.soriya.nestlive.net.LiveApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject

class LiveRepository @Inject constructor(
    private val liveApi: LiveApi
) {

    fun list(page: Int, size: Int): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        val liveList = liveApi.liveList(page, size)
        emit(liveList)
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun getByChannelId(channelId: Long): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(liveApi.getByChannelId(channelId))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun createLive(live: Live): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(liveApi.createLive(live))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun stopLive(channelId: Long): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(liveApi.stopLive(channelId))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun getHistory(channelId: Long): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(liveApi.getHistory(channelId))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

}